<template>
  <el-cascader placeholder="请选择网格"
    :show-all-levels="true"
    :options="options"
    :change-on-select="changeOnSelect"
    v-model="value"
    :filterable="true"
    :disabled="showOnly"
    @change="changeValue" />
</template>

<script>
import { getCaseOptions, getLastIdByAllId, getAllParentIdByOptions } from '@/utils/CommonUtil'
import { getUserGridTree } from '@/utils/SessionDataUtil'
export default {
  model: {
    prop: 'allGridId',
    event: 'changeGrid'
  },
  props: {
    showOnly: Boolean,
    allGridId: String,
    changeOnSelect: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      options: [],
      newValue: [],
      firstValue: []
    }
  },
  computed: {
    value: {
      get: function () {
        if (this.allGridId && this.allGridId !== '') {
          // let arr = this.allGridId.split(',')
          // arr.shift()
          // return arr
          let data = {}
          data.id = getLastIdByAllId(this.allGridId)
          data.options = this.options
          let ids = getAllParentIdByOptions(data)
          if (ids && ids instanceof Array && ids.length > 0) {
            return ids
          } else {
            return [this.allGridId]
          }
        }
      },
      set: function (newValue) {
        this.newValue = newValue
      }
    }
  },
  components: {},
  mounted () {
    this.getOptions()
  },
  methods: {
    getOptions () {
      let gridTree = getUserGridTree()
      if (gridTree && gridTree instanceof Array) {
        this.options = getCaseOptions(gridTree[0].children)
        this.firstValue = gridTree[0].id
      }
    },
    changeValue (data) {
      if (data && data instanceof Array) {
        let v = data.join(',')
        if (this.firstValue) {
          if (v.indexOf(this.firstValue) === -1) {
            v = this.firstValue + ',' + v
          }
        }
        this.$emit('changeGrid', v)
      }
    }
  }
}
</script>
